package touchpad;

import it.mouseclient.UDPClient;

import java.util.Timer;
import java.util.TimerTask;

import android.view.MotionEvent;

import common.CommandType;

public class LeftClick extends TouchpadCommand {

	private static final long DELAY_WAIT_CLICK = 800;
	private Timer timerLeftClick;
	private boolean sendLeftClick;

	public LeftClick(UDPClient client) {
		super(client);
		sendLeftClick = false;
		timerLeftClick = new Timer();
	}

	@Override
	public boolean onUpTouch(MotionEvent m) {
		boolean success=true;
		stopTimer();
		if (getSendLeftClick()) {
			if (client != null) {
				success=client.executeCommand(CommandType.LEFT_CLICK, null);
			}

		}

		setSendLeftClick(false);
		return success;
	}

	@Override
	public boolean onDownTouch(MotionEvent m) {
			setSendLeftClick(true);
			timerLeftClick.schedule(new TimerTask() {

				@Override
				public void run() {
					setSendLeftClick(false);

				}
			}, DELAY_WAIT_CLICK);
		
			return true;
	}

	@Override
	public boolean onMoveTouch(MotionEvent m) {
		stopTimer();
		setSendLeftClick(false);
		return true;
	}

	private synchronized void setSendLeftClick(boolean send) {
		this.sendLeftClick = send;
	}

	private synchronized boolean getSendLeftClick() {
		return this.sendLeftClick;
	}

	@Override
	public boolean onDownMultitouch(MotionEvent m) {
		stopTimer();
		setSendLeftClick(false);
		return true;

	}

	@Override
	public boolean onUpMultitouch(MotionEvent m) {
		// TODO Auto-generated method stub
		return true;
	}

	private void stopTimer() {
		timerLeftClick.cancel();
		timerLeftClick = new Timer();
	}

}
